﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Speech.Recognition;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace DigiMate
{
	public class TranslateService : BaseService
	{
		private string key;
		public TranslateService()
		{
			key = System.Configuration.ConfigurationManager.AppSettings["YandexTranslateKey"];
		}

		protected override Grammar GetGrammar()
		{
			GrammarBuilder grammarBuilder = new GrammarBuilder();
			grammarBuilder.Culture = reco.RecognizerInfo.Culture;
			grammarBuilder.Append(new Choices("Da", "Net", "Otmena"));
			return new Grammar(grammarBuilder);
		}

		protected override void LoadGrammar()
		{
			base.LoadGrammar();
			reco.LoadGrammar(new DictationGrammar());
		}

		public override void Run(string text)
		{
			if (inProcess)
				return;

			inProcess = true;
			try
			{
				bool shouldExit = false;
				while (!shouldExit)
				{

					Speaker.Speak("Что перевести?");

					Thread.Sleep(500);

					RecognitionResult res = reco.Recognize(TimeSpan.FromMilliseconds(3000)); // recognize speech

					if (res != null && res.Words.Count > 0)
					{
						string textToTranslate = res.Text.ToLower();
						Speaker.Speak("Вы сказали " + textToTranslate);
						reco.UnloadAllGrammars();
						Thread.Sleep(500);

						reco = GetReco();
						reco.UnloadAllGrammars();
						reco.LoadGrammar(GetGrammar());
						res = reco.Recognize(TimeSpan.FromMilliseconds(3000)); // recognize speech


						switch ((res == null ? "" : res.Text.ToLower()))
						{
							case "da":
								string translatedText = Translate("en-ru", textToTranslate);

								if (translatedText.Length > 0)
								{
									Speaker.Speak(textToTranslate + " переводится как " + translatedText);
									Speaker.Speak("Ок");
									shouldExit = true;
								
								}
								else
								{
									AddLog("Не нашла перевода для " + textToTranslate);
									shouldExit = true;
								
								}
								break;
							case "otmena":
								shouldExit = true;
								return; 

							case "net":
								AddLog("Спрашиваем снова..");
								break;

							default:
								Speaker.Speak("Тишина..");
								break;
						
						}
					}
					else
					{
						Speaker.Speak("Не поняла, выход");
						AddLog("Не поняла, выход");
						shouldExit = true;
					}
				}
			}
			catch (Exception ex)
			{
				AddLog("There was a problem with rss: " + ex.Message);
				Speaker.Speak("Ошибка " + ex.Message);
			}
			finally
			{
				AddLog("Weather Stopped.");

				inProcess = false;
			}
		}

		public string Translate(string lang, string text) //("en-ru", "тест")
		{
			try
			{
				WebRequest request = WebRequest.Create(@"http://translate.yandex.net/tr.json/translate?lang=en-ru&srv=tr-text&text=" + text);
					//+ "key=" + key
					//+ "&text =" + text
					//+ " & lang=" + lang
					//+ "& [format=plain]"
					//+ " & [options=1]");
				WebResponse response = request.GetResponse();
				using (StreamReader sr = new StreamReader(response.GetResponseStream()))
				{
					var fetchedXml = sr.ReadToEnd();
					//XmlDocument d = new XmlDocument();
					//d.LoadXml(fetchedXml);
					//XmlNodeList textNodes = d.GetElementsByTagName("text");

					//string result = "";

					//foreach (XmlNode textNode in textNodes)
					//	result += textNode.InnerText + " ";

					return fetchedXml;
				}
			}
			catch (Exception ex)
			{
				string m = "Возникла ошибка: " + ex.Message;
				AddLog(m);
				return m;
			}
		}
		
	}
}
